﻿using System;
using System.Drawing;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace LcfContols
{
    /// <summary>
    /// 底部信息
    /// </summary>
    internal class PageInfo : Control
    {

        #region 变量
        /// <summary>
        /// 当前页面条数显示区域
        /// </summary>
        private Rectangle _nowRowsRectangle = new Rectangle();

        /// <summary>
        /// 底部信息更新
        /// </summary>
        private Rectangle _buttomRectangle = new Rectangle();

        /// <summary>
        /// 当前页条数
        /// </summary>
        private int _nowRows;

        /// <summary>
        /// 当前分页中的最后一页。用来判断页码是否有变动，是否需要更新下拉框
        /// </summary>
        private uint lastPage;

        /// <summary>
        /// 页码信息
        /// </summary>
        private Page _page = new Page();
        #endregion

        #region 事件
        /// <summary>
        /// 页码更新事件
        /// </summary>
        internal event Action pgChange;
        #endregion

        #region 底部字符串
        /// <summary>
        /// 所有条数
        /// </summary>
        private string allStr = "总条数：";
        /// <summary>
        /// 当前页几条
        /// </summary>
        private string pageStr = "单页条数：";

        #endregion

        #region 属性
        public override Font Font
        {
            get
            {
                return base.Font;
            }
            set
            {
                base.Font = value;
                initializeControls();
            }
        }
        
        /// <summary>
        /// 分页数据
        /// </summary>
        public Page Page
        {
            get
            {
                return _page;
            }
            set
            {
                _page = value;
            }
        }
        #endregion

        #region 子控件
        /// <summary>
        /// 页码下拉框
        /// </summary>
        private ComboBox comboBox = new ComboBox();
        /// <summary>
        /// 上一页按钮
        /// </summary>
        private Button upBtn = new Button();
        /// <summary>
        /// 下一页按钮
        /// </summary>
        private Button downBtn = new Button();

        #endregion

        /// <summary>
        /// 显示顶部黑线
        /// </summary>
        public bool ShowTopLine
        {
            get; set;
        }

        public PageInfo(Control control)
        {
            SetStyle(
                ControlStyles.UserPaint | // 控件将自行绘制，而不是通过操作系统来绘制  
                ControlStyles.OptimizedDoubleBuffer | // 该控件首先在缓冲区中绘制，而不是直接绘制到屏幕上，这样可以减少闪烁 
                ControlStyles.AllPaintingInWmPaint | // 控件将忽略 WM_ERASEBKGND 窗口消息以减少闪烁  
                ControlStyles.ResizeRedraw | // 在调整控件大小时重绘控件 
                ControlStyles.SupportsTransparentBackColor,// 控件接受 alpha 组件小于 255 的 BackColor 以模拟透明
                true // 设置以上值为 true 
                );
            FriendControl = control;
            UpdateStyles();
            initializeControls();
            upBtn.Click += UpBtn_Click;
            downBtn.Click += DownBtn_Click;
            Controls.Add(upBtn);
            Controls.Add(comboBox);
            Controls.Add(downBtn);
            upBtn.Enabled = false;
            downBtn.Enabled = false;
            comboBox.Enabled = false;
        }

        private void DownBtn_Click(object sender, EventArgs e)
        {
            uint lastpage = Page.nowPage;
            Page.nowPage++;
            if (Page.nowPage != lastPage && pgChange != null)
                pgChange();
        }

        private void UpBtn_Click(object sender, EventArgs e)
        {
            uint lastpage = Page.nowPage;
            Page.nowPage--;
            if (Page.nowPage != lastPage && pgChange != null)
                pgChange();
        }

        /// <summary>
        /// 更新页码
        /// </summary>
        internal void UpdatePage()
        {
            SetPage(); //设置分页数据
            Invalidate(_buttomRectangle); //更新底部区域
        }

        private void SetPage()
        {
            comboBox.SelectedValueChanged -= comboBox1_SelectedIndexChanged;
            upBtn.Enabled = true;
            comboBox.Enabled = lastPage>0;
            downBtn.Enabled = true;
            upBtn.Enabled = Page.nowPage > 0;
            if (Page.allPage > 0 && Page.allPage != lastPage)
            {
                lastPage = Page.allPage;
                comboBox.Items.Clear();
                if (lastPage > 0)
                {
                    comboBox.Enabled = true;
                    for (int i = 0; i < lastPage; i++)
                    {
                        comboBox.Items.Add(i+1);
                    }
                    comboBox.SelectedIndex = 0;
                    if (lastPage == 1)
                        comboBox.Enabled = false;
                }
                else
                {
                    comboBox.Text = "";
                }
            }
            downBtn.Enabled = Page.allPage > Page.nowPage + 1;
            if(comboBox.Items.Count > Page.nowPage)
                comboBox.SelectedIndex = (int)Page.nowPage;
            comboBox.SelectedValueChanged += comboBox1_SelectedIndexChanged;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            uint lastpage = Page.nowPage;
            Page.nowPage = Convert.ToUInt32(comboBox.SelectedIndex);
#if DEBUG
            Console.WriteLine("更新页码：" + Page.nowPage);
#endif
            if (pgChange != null && Page.nowPage != lastPage)
                pgChange();
        }

        /// <summary>
        /// 设置关联控件
        /// </summary>
        public Control FriendControl { get; set; }

        protected override void OnFontChanged(EventArgs e)
        {
            base.OnFontChanged(e);
            initializeControls();
            if(FriendControl != null)
            {
                Size s = FriendControl.Size;
                s.Height -= 1;
                FriendControl.Size = s;
                s.Height += 1;
                FriendControl.Size = s;
            }
        }

        /// <summary>
        /// 更新按钮
        /// </summary>
        private void initializeControls()
        {
            Size TextSize = TextRenderer.MeasureText("<", Font);
            downBtn.Text = ">";
            downBtn.Size = new Size(TextSize.Width + 20, TextSize.Height + 10);
            upBtn.Text = "<";
            upBtn.Size = new Size(TextSize.Width + 20, TextSize.Height + 10);
            Height = downBtn.Height + 10;
        }

        /// <summary>
        /// 获取该控件的最小宽度
        /// </summary>
        /// <returns></returns>
        internal int minWidth()
        {
            return downBtn.Width + 30 + upBtn.Width + comboBox.Width;
        }

        /// <summary>
        /// 更新单页条数
        /// </summary>
        /// <param name="rows">当前页</param>
        internal void UpdateNowRows(int rows)
        {
            if (rows == _nowRows)
                return;
            _nowRows = rows;
            Invalidate(_nowRowsRectangle);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if(ShowTopLine)
                e.Graphics.DrawLine(SystemPens.WindowText, new Point(0, 0), new Point(Width, 0));
            int y = ClientRectangle.Top + (ClientRectangle.Height - downBtn.Height) / 2 + 1;
            downBtn.Location = new Point(ClientRectangle.Right - downBtn.Width - 10, y);
            Size lengthSize = TextRenderer.MeasureText(string.Format("{0}", Page.allPage), Font);
            comboBox.Width = lengthSize.Width + 40;
            comboBox.Location = new Point(downBtn.Left - comboBox.Width - 5, ClientRectangle.Top + (ClientRectangle.Height - comboBox.Height) / 2 + 1);
            upBtn.Location = new Point(comboBox.Left - upBtn.Width - 5, y);
            using (SolidBrush brush = new SolidBrush(ForeColor))
            {
                Size allSize = TextRenderer.MeasureText(allStr + Page.rows + "    " + pageStr, Font);
                Size rowSize = TextRenderer.MeasureText(string.Format("{0}", _nowRows), Font);
                if (allSize.Width + rowSize.Width + 10 + minWidth() < ClientRectangle.Width)
                {
                    e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                    e.Graphics.DrawString(allStr + Page.rows + "    " + pageStr, Font, brush, 10, 10);
                    e.Graphics.DrawString(string.Format("{0}", _nowRows), Font, brush, 5 + allSize.Width, 10);
                    _nowRowsRectangle.X = 5 + allSize.Width;
                    _nowRowsRectangle.Y = 10;
                    _nowRowsRectangle.Width = rowSize.Width;
                    _nowRowsRectangle.Height = rowSize.Height;
                    _buttomRectangle.X = 10;
                    _buttomRectangle.Y = 10;
                    _buttomRectangle.Width = 5 + allSize.Width + _nowRowsRectangle.Width;
                    _buttomRectangle.Height = Math.Max(allSize.Height, rowSize.Height);
                }
            }
        }

        /// <summary>
        /// 清楚数据
        /// </summary>
        public void Clear()
        {
            Page.nowPage = 0;
            Page.rows = 0;
            comboBox.Items.Clear();
            lastPage = 0;
        }
    }

}
